/*
   Transfer ownership of threads
*/


void some_function();
void some_other_function();
std::thread t1(some_function);   
std::thread t2 = std::move(t1);  // some_function的线程现在与t2关联
t1 = std::thread(some_other_function); // 临时的std::thread对象，自动隐式移动
std::thread t3;   
t3 = std::move(t2);
t1 = std::move(t3);  // 此时t1已关联（运行着some_other_funciton)的线程
                     // 调用std::terminate()来终止程序
// 析构前必须显式地等待线程完成或分离，同样也适用于赋值（不能通过新的std::thread对象赋值而“舍弃”-个线程


// 所有权从一个函数中转移出
std::thread f()
{
   void some_function();
   return std::thread(some_function);
}
std::thread g()
{
   void some_thread_function(int);
   std::thread t(some_other_function, 42);
   return t;
}

// 所有权转移到函数中
void f(std::thread t);
void g()
{
   void some_function();
   f(std::thread(some_function));
   std::thread t(some_function);
   f(std::move(t));
}


// scoped_thread 和示例用法
class scoped_thread
{
   std::thread t;
public:
   explicit scoped_thread(std::thread t_) : t(std::move(t))
   {
      if(!t.joinable())
         throw std::logic_error("No thread");
   }
   ~scoped_thread()
   {
      t.join();
   }
   scoped_thread(scoped_thread const&) = delete;
   scoped_thread& operator=(scoped_thread const&) = delete;
};
struct func;

void f()
{
   int some_local_state;
   scoped_thread t(std::thread(func(some_local_state)));

   do_something_in_current_thread();
}